<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/3
 * Time: 15:05
 */

use Phalcon\Logger\Adapter\File as FileAdapter;
use Phalcon\Logger\Formatter\Line as LineFormatter;

class Log
{

    private static $_log_name;
    private static $_instance;
    private $_log_dir;


    public static function instance() {
        if ( self::$_instance == null ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }


    public function set_log_dir($log_dir=__DIR__ . '/../../logs')
    {
        self::$_log_dir = $log_dir;
    }


    private function mkdirs($dir, $mode = 0777)
    {
        //echo $dir.'</br>';
        if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
        if (!self::mkdirs(dirname($dir), $mode)) return FALSE;
        return @mkdir($dir, $mode);
    }


    public function log($log_value, $log_type="DEBUG")
    {
        date_default_timezone_set('PRC');
        $year = date("Y",time());
        $month = date("m",time());
        $day = date("d",time());


        $dir_file = self::$_log_dir.'/'.$year."/".$month."/".$day;


        self::mkdirs($_dir_file);


        $log_name = new FileAdapter($dir_file."/".$day.".log");
        $formatter = new LineFormatter(" [%type%] - %message% ");//定义信息格式
        $_log_name->setFormatter($formatter);


        $_log_name->begin();

        $_log_name->alert(date("Y-m-d H:i:s",time()));
//输出时间


        if (strcasecmp($log_type, "INFO")==0) {
            $_log_name->log($log_value,\Phalcon\Logger::INFO);
//输出信息
        }
        else if(strcasecmp($log_type, "NOTICE")==0){
            $_log_name->log($log_value,\Phalcon\Logger::NOTICE);
        }
        else if(strcasecmp($log_type, "WARNING")==0||strcasecmp($_log_type, "WARN")==0){
            $_log_name->log($log_value,\Phalcon\Logger::WARNING);
        }
        else if(strcasecmp($log_type, "ERROR")==0){
            $_log_name->log($log_value,\Phalcon\Logger::ERROR);
        }
        else {
            $_log_name->log($log_value,\Phalcon\Logger::DEBUG);
        }

        $_log_name->commit();
        $_log_name->close();
    }




}